package com.mezz.bones.im.logic.service.impl;

import com.mezz.bones.im.common.domain.user.ImUserConnectInfo;
import com.mezz.bones.im.common.enums.ActionCodeEnum;
import com.mezz.bones.im.common.event.MessageReceivedEvent;
import com.mezz.bones.im.common.event.MessageSendWithUserIdEvent;
import com.mezz.bones.im.common.message.base.Message;
import com.mezz.bones.im.common.message.base.MessageHeader;
import com.mezz.bones.im.common.message.body.in.PrivateMessageCreateReq;
import com.mezz.bones.im.common.message.body.out.PrivateMessageCreateRes;
import com.mezz.bones.im.common.message.body.out.PrivateMessageRecordRes;
import com.mezz.bones.im.common.process.IMessageProcessor;
import com.mezz.bones.im.common.util.MessageUtil;
import com.mezz.bones.im.logic.domain.request.ApiPrivateMessageCreateRequest;
import com.mezz.bones.im.logic.service.IApiPrivateMessageService;
import com.mezz.bones.im.logic.service.IMessageReceiveService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author: zhuang
 * @Date: 2025/5/15 17:46
 * @Description: TODO
 * @Version: 1.0
 **/

@Service
@Slf4j
@AllArgsConstructor
public class IApiPrivateMessageServiceImpl implements IApiPrivateMessageService {

    private final IMessageReceiveService messageReceiveService;
    private final IMessageProcessor messagePublisher;

    @Override
    public void apiCreatePrivateMessage(ApiPrivateMessageCreateRequest request) {

        //构建消息发送入口参数
        ImUserConnectInfo senderUserConnectInfo = buildSenderUserInfo();
        Message message = buildMessage(request);
        MessageHeader header = message.getHeader();
        MessageReceivedEvent event = new MessageReceivedEvent(senderUserConnectInfo, message);
        Object res = messageReceiveService.handleMessage(event);
        if(res == null){
            return;
        }

        PrivateMessageCreateRes createRes = (PrivateMessageCreateRes) res;
        //是否需要推送消息到己方 因为是后台API形式发送的消息 可能己方也要补充这个推送消息
        if(request.getPush2User() == null || request.getPush2User() == 1) {
            //
            PrivateMessageRecordRes pushUserData = buildPushUserMessageModel(message,request,createRes);
            //保持跟 用户主动拉消息的一致性
            List<PrivateMessageRecordRes> messagePushData = List.of(pushUserData);
            messagePublisher.sendMessage2UserId(new MessageSendWithUserIdEvent(header.getTraceId(), ActionCodeEnum.CLIENT_PRIVATE_MESSAGE_RECORD.getCode(), messagePushData, request.getUserId()));
        }
    }

    private PrivateMessageRecordRes buildPushUserMessageModel(Message message, ApiPrivateMessageCreateRequest request, PrivateMessageCreateRes createRes) {

        PrivateMessageCreateReq body = ((PrivateMessageCreateReq) message.getBody());

        PrivateMessageRecordRes res = new PrivateMessageRecordRes();
        res.setId(createRes.getUserMsgRecordId());
        res.setMsgKey(body.getMsgKey());

        //用户ID应该是接收者自身 接入层会通过此ID去查询到具体的 连接channel
        res.setUserId(request.getUserId());

        //对应接收者对端 就是消息发送者
        res.setPeerId(request.getPeerId());

        //消息是发送
        res.setDirection(0);
        res.setMsgSeq(body.getMsgSeq());
        res.setMsgType(body.getMsgType());
        res.setContentType(body.getContentType());
        res.setContent(body.getContent());
        res.setMsgExtra(body.getMsgExtra());
        res.setUserRecalled(0);
        res.setCreateTime(createRes.getNow());
        return res;
    }
    private Message buildMessage(ApiPrivateMessageCreateRequest request) {

        Date now = new Date();


        Message message = new Message();
        MessageHeader header = new MessageHeader();
        message.setHeader(header);
        header.setActionCode(ActionCodeEnum.CLIENT_PRIVATE_MESSAGE_CREATE.getCode());
        header.setTraceId(UUID.randomUUID().toString());
        header.setTimestamp(now.getTime());
        header.setDeviceType("admin");
        header.setImei("admin");
        header.setAck(false);

        PrivateMessageCreateReq req = new PrivateMessageCreateReq();
        req.setUserId(request.getUserId());
        req.setPeerId(request.getPeerId());
        req.setRelationId(request.getRelationId());
        req.setMsgKey(UUID.randomUUID().toString());
        req.setMsgSeq(MessageUtil.generateMessageSeq());
        req.setMsgType(request.getMsgType());
        req.setSync2Peer(request.getSync2Peer());
        req.setContentType(request.getContentType());
        req.setContent(request.getContent());
        req.setMsgExtra(request.getMsgExtra());
        message.setBody(req);
        return message;
    }


    private ImUserConnectInfo buildSenderUserInfo() {

        return ImUserConnectInfo.builder()
                .userId("admin")
                .userType("admin")
                .deviceType("admin")
                .imei("admin")
                .ip("0.0.0.0")
                .build();
    }
}
